/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package inputsms.utilities;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import inputsms.model.Content;
import inputsms.model.Sms;
import org.apache.log4j.Logger;

/**
 *
 * @author aisyah
 */
public class Read implements Runnable {

    private static Logger logger = Logger.getLogger(Read.class);
    private boolean isRun = true;

    public void run() {
        while (isRun) {
            try {
                Thread.sleep(5000);
                this.readData(Property.getProperty("dir.mo.operator"));

            } catch (InterruptedException ex) {
                logger.error("file " + Property.getProperty("dir.mo.operator"));
            }
        }
    }

    private boolean checkFileOnList(String operator, String path) {
        boolean isExist = false;
        File dir = new File(path);
        File[] listOfDir = dir.listFiles();
        for (int i = 0; i < listOfDir.length; i++) {
            System.out.println("list name file= " + listOfDir[i].getName());
            if (listOfDir[i].getName().equalsIgnoreCase(operator + ".properties")) {
                isExist = true;
                break;
            }
        }
        return isExist;
    }

    public void readData(String input) {
        boolean succes = true;
        File folder = new File(input);
        File[] listOfFiles = folder.listFiles();
        try {
            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    System.out.println("Processing " + listOfFiles[i].getName());
                    File file = listOfFiles[i];
                    FileInputStream fis = null;
                    BufferedInputStream bis = null;
                    DataInputStream dis = null;
                    BufferedReader br = null;

                    try {
                        fis = new FileInputStream(file);
                        bis = new BufferedInputStream(fis);
                        dis = new DataInputStream(bis);
                        br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                        System.out.println("proses file =" + file.getName());
                        String[] temp = new String[3];
                        for (int ii = 0; ii < 3; ii++) {
                            temp[ii] = br.readLine();
                        }

                        System.out.println("array read data " + temp[0].trim() + "-" + temp[1] + "-" + temp[2]);

                        Sms sms = new Sms();
                        sms.setMsisdn(temp[0]);
                        sms.setOperator_id(temp[1]);

                        //check file operator
                        if (checkFileOnList(temp[1], Property.getProperty("dir.conf.operator"))) {
                            //prepare insert to model
                            Content co = new MapKey(temp[2], temp[1]).getContent();
                            System.out.println("co key " + co.getKey());
                            System.out.println("co isi " + co.getIsi());
                            // insert to model
                            sms.setKey(co.getKey());

                            if (co.getIsi() != null) {
                                //if REG FB or FB CHANGE
                                if ((sms.getKey().equalsIgnoreCase(DefaultKey.REG_FB)) || (sms.getKey().equalsIgnoreCase(DefaultKey.FB_CHANGE))) {
                                    if (EmailValidator.validate(co.getIsi().split(" ")[0]) && co.getIsi().split(" ").length > 1) {
                                        sms.setEmail(co.getIsi().split(" ")[0]);
                                        sms.setPassword(co.getIsi().split(" ")[1]);

                                    } else {
                                        sms.setKey(Property.getProperty("dir.fault"));
                                        sms.setContent(MessageId.DONT_PROVIDE_UID);
                                        logger.error(Property.getProperty("msg.failed.provide"));
                                    }

                                } else if (sms.getKey().equalsIgnoreCase(DefaultKey.FB_TO)) { //if FB TO
                                    if (co.getIsi().split(" ").length > 1) {
                                        sms.setBuddyId(co.getIsi().split(" ")[0].toLowerCase());
                                        sms.setContent(co.getIsi().split(" ")[1]);
                                    } else {
                                        sms.setKey(Property.getProperty("dir.fault"));
                                        sms.setContent(MessageId.FB_TO_FORMAT_NOT_VALID);
                                        logger.error(Property.getProperty("msg.failed.fbto.format"));
                                    }
                                } else if (co.getIsi().equalsIgnoreCase(MessageId.COMMAND_NOT_FOUND)) {//key not found
                                    sms.setContent(co.getIsi());
                                    System.out.println("split..........:" + temp[2].split(" ").length);
                                    if (temp[2].split(" ").length >= 2) {
                                        sms.setMsg(temp[2].split(" ")[0]+" "+ temp[2].split(" ")[1]);
                                    } else {
                                        sms.setMsg(temp[2].split(" ")[0]);
                                    }
                                } else {
                                    sms.setContent(co.getIsi());
                                }
                            }
                        } else {
                            sms.setContent(Property.getProperty("msg.failed.operator"));
                            sms.setKey(Property.getProperty("dir.fault"));
                        }



                        //create file
                        this.createFile(sms);

                        /*
                        //add if help
                        if (sms.getKey().equalsIgnoreCase(DefaultKey.FB_HELP)) {
                        sms.setKey(Property.getProperty("dir.fault"));
                        sms.setContent(MessageId.HELP);
                        //create file
                        this.createFile(sms);
                        System.out.println("HElP");
                        } else if (sms.getKey().equalsIgnoreCase(DefaultKey.FB_HELP_MORE)) {
                        sms.setKey(Property.getProperty("dir.fault"));
                        sms.setContent(MessageId.HELP_MORE);
                        //create file
                        this.createFile(sms);
                        System.out.println("HELP MORE");
                        }
                         *
                         */
                        fis.close();
                        bis.close();
                        dis.close();
                        br.close();

                        listOfFiles[i].delete();
                        succes = true;
                    } catch (FileNotFoundException e) {
                        logger.error("file not fount ");


                    } catch (IOException e) {
                        logger.error("IOException ");
                        succes = false;
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("catch 1");
            logger.error("file " + Property.getProperty("dir.mo.operator") + " not found");
            setIsRun(false);
        }
//        return succes;
    }

    private void createFile(Sms sms) {
        CreateFile cr = new CreateFile(sms);
        if (cr.writeFile()) {
            if (!sms.getKey().equalsIgnoreCase(Property.getProperty("dir.fault"))) {
                logger.info("succes save msisdn " + sms.getMsisdn());
            } else {
                logger.info("failed msisdn " + sms.getMsisdn() + ":" + sms.getContent());
            }
        } else {
            this.setIsRun(false);
        }
    }

    public boolean isIsRun() {
        return isRun;
    }

    public void setIsRun(boolean isRun) {
        this.isRun = isRun;
    }
}
